// 创建一个Web Worker实例
const createWorker = (isFile, workerScript) => {
  console.log(workerScript)
  if (!isFile) {
    const blob = new Blob([`(${workerScript.toString()})()`], {
      type: 'text/javascript'
    })
    const url = window.URL.createObjectURL(blob)
    return new Worker(url, {
      type: 'module' // 指定 worker.js 的类型
    })
  } else if (isFile) {
    return new Worker(new URL(workerScript, import.meta.url).href, {
      type: 'module' // 指定 worker.js 的类型
    })
  }
}

function useBaseWebWorker(isFile, workerScript) {
  const worker = ref(createWorker(isFile, workerScript))
  const message = ref<any>(null)
  const error = ref<any>(null)

  worker.value.onmessage = e => {
    message.value = e.data
    error.value = null
  }

  worker.value.onerror = e => {
    message.value = null
    error.value = e
  }

  const postMessage = msg => worker.value.postMessage(msg)

  onUnmounted(() => worker.value.terminate())

  return { postMessage, message, error }
}

export default useBaseWebWorker
